#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/12/18 16:05
# @Author  : leon yan
# @Site    : 
# @File    : qPlcFlash.py
# @Software: PyCharm

import time
from threading import Lock

from PyQt5.QtCore import QObject
import lib.applets as sApp
import Globalist as gl


class QPlcPolling(QObject):
    def __init__(self):
        super().__init__()
        # init a thread lock
        self.regs_lock = Lock()
        ''''''

    def plc_thread(self):
        while True:
            read_plc_status()
            read_power()
            writeLinkSignal()
            writeOnline()
            writeConveyorSpeed()
            writeCloud()
            ip2ip()
            # 0.1s before next polling
            time.sleep(0.1)


def read_plc_status():
    """
    急停，报警，运行存放在"Plc_read_area"的dataType1里
    """
    data_type1 = gl.global_var["Plc_read_area"]["data_rdArea1"]["dArea"]
    '''急停'''
    aa = gl.global_var["PlcAddress_emergency"]
    i = 0
    for k, v in aa.items():
        if v[1] > 0:
            bb = data_type1[v[0]]
            if bb[0] == "bit":
                gl.global_var["bEmergencyStopList"][i] = bb[2][v[1]-bb[1]]
            elif bb[0] == "word":
                aa1 = v[1] // 16    # 第几个字
                aa2 = v[1] % 16     # 第几个位
                aa3 = sApp.int2bin(bb[2][aa1])[aa2]
                gl.global_var["bEmergencyStopList"][i] = aa3
        i += 1

    '''报警'''
    aa = gl.global_var["PlcAddress_alarm"]
    i = 0
    for k, v in aa.items():
        if v[1] > 0:
            bb = data_type1[v[0]]
            if bb[0] == "bit":
                gl.global_var["bAlarmList"][i] = bb[2][v[1]-bb[1]]
            elif bb[0] == "word":
                aa1 = v[1] // 16    # 第几个字
                aa2 = v[1] % 16     # 第几个位
                aa3 = sApp.int2bin(bb[2][aa1])[aa2]
                gl.global_var["bAlarmList"][i] = aa3
        i += 1

    '''运行'''
    aa = gl.global_var["PlcAddress_running"]
    i = 0
    for k, v in aa.items():
        if v[1] > 0:
            bb = data_type1[v[0]]
            if bb[0] == "bit":
                gl.global_var["bRunningList"][i] = bb[2][v[1]-bb[1]]
            elif bb[0] == "word":
                aa1 = v[1] // 16    # 第几个字
                aa2 = v[1] % 16     # 第几个位
                aa3 = sApp.int2bin(bb[2][aa1])[aa2]
                gl.global_var["bRunningList"][i] = aa3
        i += 1


def read_height():
    eHeightDict = gl.global_var["Plc_Interface"]["D2010"]
    aa = gl.global_var["Plc_Interface"]["4X0"]["9"]
    if aa:
        eSander1Height = float(aa[2]) / 100.0
    else:
        eSander1Height = 0.0
    aa2 = gl.global_var["Plc_Interface"]["4X0"]["14"]
    if aa2:
        eSander2Height = float(aa2[2]) / 100.0
    else:
        eSander2Height = 0.0

    gl.global_var["curHeight"]["1"] = [float(u2s(eHeightDict["1"][0])) / 10.0]
    gl.global_var["curHeight"]["3"] = [float(u2s(eHeightDict["3"][0])) / 10.0, float(u2s(eHeightDict["3"][1])) / 10.0]
    gl.global_var["curHeight"]["4"] = [float(u2s(eHeightDict["4"][0])) / 10.0, float(u2s(eHeightDict["4"][1])) / 10.0]
    gl.global_var["curHeight"]["7"] = [float(u2s(eHeightDict["7"][0])) / 10.0, float(u2s(eHeightDict["7"][1])) / 10.0,
                                       float(u2s(eHeightDict["7"][2])) / 10.0]
    gl.global_var["curHeight"]["9"] = [eSander1Height]
    gl.global_var["curHeight"]["10"] = [float(u2s(eHeightDict["10"][0])) / 10.0, float(u2s(eHeightDict["10"][1])),
                                        float(u2s(eHeightDict["10"][2])) / 10.0]
    gl.global_var["curHeight"]["12"] = [float(u2s(eHeightDict["12"][0])) / 10.0,
                                        float(u2s(eHeightDict["12"][1])) / 10.0]
    gl.global_var["curHeight"]["14"] = [eSander2Height]
    gl.global_var["curHeight"]["15"] = [float(u2s(eHeightDict["15"][0])) / 10.0]

    eSetHeightDict = gl.global_var["Plc_Interface"]["D3000"]
    gl.global_var["setHeight"]["1"] = [float(u2s(eSetHeightDict["1"][0])) / 10.0]
    gl.global_var["setHeight"]["3"] = [float(u2s(eSetHeightDict["3"][0])) / 10.0,
                                       float(u2s(eSetHeightDict["3"][1])) / 10.0]
    gl.global_var["setHeight"]["4"] = [float(u2s(eSetHeightDict["4"][0])) / 10.0,
                                       float(u2s(eSetHeightDict["4"][1])) / 10.0]
    gl.global_var["setHeight"]["7"] = [float(u2s(eSetHeightDict["7"][0])) / 10.0,
                                       float(u2s(eSetHeightDict["7"][1])) / 10.0,
                                       float(u2s(eSetHeightDict["7"][2])) / 10.0]
    gl.global_var["setHeight"]["9"] = [eSander1Height]
    gl.global_var["setHeight"]["10"] = [float(u2s(eSetHeightDict["10"][0])) / 10.0, float(u2s(eSetHeightDict["10"][1])),
                                        float(u2s(eSetHeightDict["10"][2])) / 10.0]
    gl.global_var["setHeight"]["12"] = [float(u2s(eSetHeightDict["12"][0])) / 10.0,
                                        float(u2s(eSetHeightDict["12"][1])) / 10.0]
    gl.global_var["setHeight"]["14"] = [eSander2Height]
    gl.global_var["setHeight"]["15"] = [float(u2s(eSetHeightDict["15"][0])) / 10.0]


def read_power():
    aa = gl.global_var["watt_hour_meter_ip"]
    aa2 = 0.0
    if aa:
        aa3 = True
        for k, v in aa.items():
            if v[2] == 0:
                aa3 = False
                break
            else:
                aa2 += v[2]
        if aa3:
            gl.global_var["monitorVar"]["TotalPower"] = round(aa2, 2)


def u2s(sData):
    if sData > 32767:
        return sData - 65536
    else:
        return sData


'''连锁信号'''


def writeLinkSignal():
    return
    M = gl.global_var["Plc_Interface"]["M600"]
    gl.global_var["Plc_write"]["link_signal"]["0"][1] = [M["1"][6]]
    gl.global_var["Plc_write"]["link_signal"]["1"][1] = [M["2"][5]]
    gl.global_var["Plc_write"]["link_signal"]["2"][1] = [M["3"][5], M["4"][5]]
    gl.global_var["Plc_write"]["link_signal"]["3"][1] = [M["2"][6]]
    gl.global_var["Plc_write"]["link_signal"]["4"][1] = [M["5"][5]]
    gl.global_var["Plc_write"]["link_signal"]["5"][1] = [M["6"][5]]
    gl.global_var["Plc_write"]["link_signal"]["6"][1] = [M["6"][6], M["7"][5]]
    gl.global_var["Plc_write"]["link_signal"]["7"][1] = [M["8"][5]]
    gl.global_var["Plc_write"]["link_signal"]["8"][1] = [M["8"][6], 1]
    # gl.global_var["link_signal"]["9"][1] = 1
    gl.global_var["Plc_write"]["link_signal"]["10"][1] = [M["11"][5]]
    gl.global_var["Plc_write"]["link_signal"]["11"][1] = [M["12"][5], M["10"][5]]
    gl.global_var["Plc_write"]["link_signal"]["12"][1] = [M["13"][5]]
    gl.global_var["Plc_write"]["link_signal"]["13"][1] = [M["13"][6], 1]
    # gl.global_var["link_signal"]["14"][1] = 1
    gl.global_var["Plc_write"]["link_signal"]["15"][1] = [M["15"][6], M["16"][5]]


# 联机信号

def writeOnline():
    bOnline = gl.global_var["operateVar"]["bLineOn"]
    aa = gl.global_var["Plc_write"]["bOnlineDict"]
    for key, value in aa.items():
        gl.global_var["Plc_write"]["bOnlineDict"][key][1] = [bOnline]


def writeConveyorSpeed():
    eConveyor = int(gl.global_var["operateVar"]["lineVelocitySet"] * 10)
    for key, value in gl.global_var["Plc_write"]["SpeedSet"].items():
        gl.global_var["Plc_write"]["SpeedSet"][key][1] = [eConveyor]


def writeCloud():
    gl.global_var["monitorVar"]["cloudBitData"][0] = gl.global_var["statusVar"]["bRunning"]
    gl.global_var["monitorVar"]["cloudBitData"][1] = gl.global_var["statusVar"]["bAlarm"]
    gl.global_var["monitorVar"]["cloudBitData"][2] = gl.global_var["statusVar"]["bReady"]

    aa = sApp.DWd2SWd(int(gl.global_var["monitorVar"]["TotalPower"]))
    gl.global_var["monitorVar"]["cloudWordData"][0] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][1] = aa[1]
    aa = sApp.DWd2SWd(int(gl.global_var["monitorVar"]["TodayPower"]))
    gl.global_var["monitorVar"]["cloudWordData"][2] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][3] = aa[1]
    aa = sApp.DWd2SWd(int(gl.global_var["monitorVar"]["TotalAmount"]))
    gl.global_var["monitorVar"]["cloudWordData"][4] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][5] = aa[1]
    aa = sApp.DWd2SWd(int(gl.global_var["monitorVar"]["TodayAmount"]))
    gl.global_var["monitorVar"]["cloudWordData"][6] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][7] = aa[1]

    gl.global_var["monitorVar"]["cloudWordData"][8] = int(gl.global_var["monitorVar"]["CurSpeed"] * 10)

    aa = sApp.DWd2SWd(gl.global_var["monitorVar"]["WorkTime"])
    gl.global_var["monitorVar"]["cloudWordData"][10] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][11] = aa[1]

    aa1 = gl.global_var["monitorVar"]["PowerTime"]
    aa2 = gl.global_var["monitorVar"]["WorkTime"]
    aa3 = gl.global_var["monitorVar"]["AlarmTime"]
    aa4 = sApp.DWd2SWd(aa1 - aa2 - aa3)
    gl.global_var["monitorVar"]["cloudWordData"][12] = aa4[0]
    gl.global_var["monitorVar"]["cloudWordData"][13] = aa4[1]

    aa = sApp.DWd2SWd(gl.global_var["monitorVar"]["AlarmTime"])
    gl.global_var["monitorVar"]["cloudWordData"][14] = aa[0]
    gl.global_var["monitorVar"]["cloudWordData"][15] = aa[1]


# ip合并 --更新通讯状态
def ip2ip():
    for key, value in gl.global_var["deviceDict"].items():
        ip = value[2]
        for sK, sV in gl.global_var["deviceIpDict"].items():
            if sV[0] == ip:
                gl.global_var["deviceDict"][key][3] = sV[1]
